#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理器
"""

import json
import os
from typing import Dict, Any

class Config:
    """配置管理类"""
    
    def __init__(self, config_file="config.json"):
        self.config_file = config_file
        self.config_data = self.load_config()
    
    def load_config(self) -> Dict[str, Any]:
        """加载配置"""
        default_config = {
            "window": {
                "width": 800,
                "height": 600,
                "resizable": True,
                "title": "挖矿模拟器：摸鱼版"
            },
            "floating_window": {
                "width": 300,
                "height": 200,
                "always_on_top": True,
                "transparency": 0.9
            },
            "game": {
                "auto_save_interval": 60,  # 自动保存间隔（秒）
                "update_interval": 100,    # UI更新间隔（毫秒）
                "enable_sound": True,
                "enable_notifications": True
            },
            "theme": {
                "bg_color": "#f0f0f0",
                "text_color": "#333333",
                "button_color": "#4CAF50",
                "accent_color": "#FF9800"
            }
        }
        
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                    # 合并默认配置和加载的配置
                    self._merge_config(default_config, loaded_config)
                    return default_config
            except Exception as e:
                print(f"配置文件加载失败: {e}")
                return default_config
        else:
            # 创建默认配置文件
            self.save_config(default_config)
            return default_config
    
    def _merge_config(self, default: Dict, loaded: Dict):
        """递归合并配置"""
        for key, value in loaded.items():
            if key in default:
                if isinstance(value, dict) and isinstance(default[key], dict):
                    self._merge_config(default[key], value)
                else:
                    default[key] = value
    
    def save_config(self, config_data=None):
        """保存配置"""
        if config_data is None:
            config_data = self.config_data
            
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"配置文件保存失败: {e}")
    
    def get(self, key: str, default=None):
        """获取配置项"""
        keys = key.split('.')
        value = self.config_data
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def set(self, key: str, value: Any):
        """设置配置项"""
        keys = key.split('.')
        current = self.config_data
        
        for k in keys[:-1]:
            if k not in current:
                current[k] = {}
            current = current[k]
        
        current[keys[-1]] = value
        self.save_config()